# -*- coding:utf-8 -*-
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom
import shutil


db_host   = "192.168.11.6"
db_user   = 'xyzs'
db_passwd = 'ikF5NNeJg2G8'
db_port   = 3309
db_name   = "app_xyapplist"


def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def copy_rename(old_file_name, new_file_name):
    src_dir= os.curdir
    dst_dir= os.path.join(os.curdir , "subfolder")
    src_file = os.path.join(src_dir, old_file_name)
    shutil.copy(src_file,dst_dir)
    
    dst_file = os.path.join(dst_dir, old_file_name)
    new_dst_file_name = os.path.join(dst_dir, new_file_name)
    os.rename(dst_file, new_dst_file_name)

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :
            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''

            index   = data.rfind('itemId')
            if index != -1:
                index_right = data.find('</integer>', index)
                itunesid = data[index: index_right]
                itunesid = itunesid.replace("itemId</key>" , '').replace("<integer>", "").strip()
            else:
                itunesid = ''
            
            return  version,bundleVersion,itunesid
        else:
            return '','',''
    except:
        return '','',''

conn = MySQLdb.connect(host=db_host,user=db_user,passwd=db_passwd,port=db_port,init_command="set names utf8")
conn.select_db(db_name)
cur  = conn.cursor()

info = "/data/app_tmp3/ipacrack2/"
listfile=os.listdir(info)
root_path = "/data/app/jailbreak/"
for line in listfile:
    return_value = get_version(unicode( info+line , "utf8" ))
    version_j = return_value[0]
    bundleVersion_j = return_value[1]
    itunesid  = return_value[2]
    if itunesid != '':
        # time.sleep(1)
        m = hashlib.md5(str(itunesid)) 
        m.digest()
        md5  = m.hexdigest()
        x    = md5[0: 1]
        str1 = md5[0: 2]
        str2 = md5[2: 4]

        if not os.path.exists(root_path+str1):
            os.mkdir(root_path+str1)
        if not os.path.exists(root_path+str1+"/"+str2):
            os.mkdir(root_path+str1+"/"+str2)

        random_filename = root_path+ str1 + "/" + str2 +"/"+ str(itunesid) + '.ipa'

        copy_rename(unicode( info+line , "utf8" ) , random_filename)

        print random_filename+"\n"

        if os.path.exists(random_filename):
            tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+str(str1)

            sql  = "select itunesid,version,bundleVersion from "+tb_name+" where itunesid='"+itunesid+"' limit 1;";
            cur.execute(sql)
            result = cur.fetchone()
            if result:
                update_sql  = "update "+tb_name+" set version_j='"+str(version_j)+"',bundleVersion_j='"+str(bundleVersion_j)+"',is_jailbreak=1,is_j_install=1 where itunesid = '"+str(itunesid)+"' limit 1;";
                print update_sql+"\n"
                commom_log('update_jailbreak_sql.log' , update_sql +  "\n" , 'a')
                cur.execute(update_sql)
            else:
                commom_log('update_jailbreak_error_sql.log' , itunesid + "---" + line +  "\n" , 'a')
        else:
            commom_log('update_copy_error_sql.log' , itunesid + "---" + line +  "\n" , 'a')

cur.close()
conn.close()